//
//  BCScanViewController.swift
//  BarCode
//
//  Created by xxcao on 2017/3/31.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//

import UIKit

class BCScanViewController: LBXScanViewController {
    //底部显示的功能项
    var bottomItemsView: UIView?
    //标识从哪一个页面进入
    var pageFrom: String?
    //切换按钮
    var btnChange:UIButton = UIButton().then {
        let size = CGSize(width: 65, height: 87);
        $0.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        $0.setImage(UIImage(named: "CodeScan.bundle/qrcode_scan_btn_flash_nor"), for:UIControlState.normal)
        $0.addTarget(self, action: #selector(openOrCloseFlash), for: .touchUpInside)
    }
    
    /**
     @brief  闪关灯开启状态
     */
    var isOpenedFlash:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        qrCodeMode()
        self.returnBack = {()-> Void in
            self.backToPrevious()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        drawBottomItems()
    }
    
    func drawBottomItems() {
        if (bottomItemsView != nil) {
            return;
        }
        let yMax = self.view.frame.maxY - self.view.frame.minY
        bottomItemsView = UIView(frame:CGRect(x: 0.0, y: yMax - 100, width: self.view.frame.size.width, height: 100))
        bottomItemsView!.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.6)
        view.addSubview(bottomItemsView!)
        
        btnChange.center = CGPoint(x: bottomItemsView!.frame.width / 2.0, y: bottomItemsView!.frame.height / 2.0)
        bottomItemsView?.addSubview(btnChange)
    }
    
    override func backToPrevious() {
        if pageFrom == "Main" {
            Common.customPopAnimationFromNavigation(nav: navigationController!, type: "cameraIrisHollowClose", subType: kCATransitionFromLeft, duration: 0.618)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
    
    //开关闪光灯
    @objc private func openOrCloseFlash() {
        scanObj?.changeTorch();
        
        isOpenedFlash = !isOpenedFlash
        
        if isOpenedFlash {
            btnChange.setImage(UIImage(named: "CodeScan.bundle/qrcode_scan_btn_flash_down"), for:UIControlState.normal)
        } else {
            btnChange.setImage(UIImage(named: "CodeScan.bundle/qrcode_scan_btn_flash_nor"), for:UIControlState.normal)
        }
    }

    override func scanResult(resultStr: String, typeStr: String) {
        //增加判断
        BmobManager.isExistRecord(table: "goods", key: "goods_code", value: resultStr) { (res, status) -> (Void) in
            if(status == .NRSSuccess) {
                if((res as! [Any]).count > 0){
                    //add code info
                    globalTuples?.code = resultStr
                    globalTuples?.goodsName = ((res as! [Any]).first as! BmobObject).object(forKey: "goods_name") as! String
                    
                    if globalTuples?.person != nil && (globalTuples?.person.characters.count)! > 0 {
                        let alert = UIAlertView(title: "提示", message: "确认要绑定"+"【"+(globalTuples?.person)!+"】"+"和扫码信息？", delegate: self, cancelButtonTitle: "取消", otherButtonTitles:"绑定")
                        alert.show()
                    } else {
                        SVProgressHUD.showInfo(withStatus: "扫码完毕，选择人员")
                        SVProgressHUD.dismiss(withDelay: 1.0)
                        let searchVC = BCSearchViewController()
                        //返回选中搜索的结果
                        searchVC.didSelectedItem { item in
                            print(item!)
                        }
                        self.navigationController?.pushViewController(searchVC, animated: true)
                    }
                }
                else {
                    SVProgressHUD.showInfo(withStatus: "不存在该货物或已没有库存，请重试")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0, execute: {
                        self.startScan()
                    })
                }
            }
            else {
                SVProgressHUD.showError(withStatus: res as! String)
            }
        }
    }
    
    //MARK: ----框内区域识别
    func qrCodeMode() {
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        style.centerUpOffset = 44
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On
        style.photoframeLineW = 6
        style.photoframeAngleW = 24
        style.photoframeAngleH = 24
        style.isNeedShowRetangle = true
        
        style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid
        
        //矩形框离左边缘及右边缘的距离
        style.xScanRetangleOffset = 80
        
        //使用的支付宝里面网格图片
        style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net")
        
        self.title = "扫一扫"
        self.scanStyle = style
        self.isOpenInterestRect = true
    }
    
    //MARK: -------条形码扫码界面 ---------
    func barCodeMode() {
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        
        style.centerUpOffset = 44
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner
        style.photoframeLineW = 4
        style.photoframeAngleW = 28
        style.photoframeAngleH = 16
        style.isNeedShowRetangle = false
        
        style.anmiationStyle = LBXScanViewAnimationStyle.LineStill
        
        style.animationImage = createImageWithColor(color: UIColor.red)
        //非正方形
        //设置矩形宽高比
        style.whRatio = 4.3/2.18
        
        //离左边和右边距离
        style.xScanRetangleOffset = 30
        
        self.title = "扫一扫"
        self.scanStyle = style
        self.isOpenInterestRect = true
    }
    
    func createImageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return theImage!
    }
}

extension BCScanViewController: UIAlertViewDelegate {
    public func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        if buttonIndex == 1 {
            SVProgressHUD.show()
            BmobManager.binding(userName: (globalTuples?.userId)!, fullName: (globalTuples?.person)!, department: (globalTuples?.department)!, code: (globalTuples?.code)!, goodsName: (globalTuples?.goodsName)!, result: { (result, status) -> (Void) in
                SVProgressHUD.dismiss()
                if(status == .NRSSuccess) {
                    SVProgressHUD.showSuccess(withStatus: "绑定成功")
                    //更新库存
                    BmobManager.updateStock(goods_code: (globalTuples?.code)!, result: { (result2, status) -> (Void) in
                        if (status == .NRSFailure) {
                            SVProgressHUD.showError(withStatus: result2 as! String)
                        }
                    })
                } else {
                    SVProgressHUD.showError(withStatus: result as! String)
                }
                Common.clearGlobalTuples()
                self.navigationController?.popToRootViewController(animated: true)
            })
        } else {
            Common.clearGlobalTuples()
            navigationController?.popToRootViewController(animated: true)
        }
    }
}


extension UIButton {
    func verticalImageAndTitle(spacing: Float) {
        let imageSize = self.imageView?.frame.size
        var titleSize = self.titleLabel?.frame.size
        
        let text : NSString = NSString(format: "%@", (self.titleLabel?.text)!)
        let textSize = text.size(attributes: [NSFontAttributeName : self.titleLabel?.font as Any])
        let frameSize = CGSize(width: ceil(textSize.width), height: ceil(textSize.height))
        if ((titleSize?.width)! + 0.5 < frameSize.width) {
            titleSize?.width = frameSize.width;
        }
        let totalHeight = Float((imageSize?.height)!) + Float((titleSize?.height)!) + spacing
        let top1 = -(totalHeight - Float((imageSize?.height)!))
        let top2 = -(totalHeight - Float((titleSize?.height)!))
        self.imageEdgeInsets = UIEdgeInsetsMake(CGFloat(top1), 0.0, 0.0, -(titleSize?.width)!)
        self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize!.width, CGFloat(top2), 0);
        self.titleLabel?.center = CGPoint(x: self.center.x, y: (self.titleLabel?.center.y)!)
    }
}
